懶得想前言了,直接進入主題 ————
今天要來講的是 : Vue 的狀態管理工具 - Vuex,顧名思義就是將資料集中在同一處管理,並且提供不同元件去讀取共享的資料,進而達成不同的元件間的資料共享。

從官方文件的這張圖中,我們可以簡單來了解一下 Vuex 的 state,actions和 mutations 都是什麼意思 :
所以我們可以再看一次上面那張圖,Vuex 資料流動的整個流程大致如下 :
我們會先在 State 儲存狀態,當元件需要被更動狀態時,我們就透過 Actions 發出 Commit 去呼叫 Mutations,再透過 Mutations 去更新 State 的狀態。
但實際上這張圖還有兩個可補充的點 :

接下來直接看 code 。 一個基本的 Vuex 大概是長這樣 :
const store = new Vuex.Store({
  state: {
   // 資料儲存的地方
  },
  mutations: {
   // 透過 mutation 修改資料狀態
  },
  actions: {
   // 打 API 的地方與操作方法的地方
  },
  getters: {
    // 取得後端傳來的資料後可做修改的地方
  }
});
好的,那我們現在來跟著以上那張圖,在 store 裡面放資料看看吧 ~
//元件
computed(){
    // 把資料從 store 讀回 component 裡面
    day:{
        get(){
            return this.store.state.day
        },
        set(val){
            // 因為開啟嚴謹模式,我們不能直接去改 day 的值
            //return this.store.state.day = val
            this.$store.commit("SETDAY",val)
        }
    },
    list(){
        return this.store.state.list
    },
},
mounted(){
    // 呼叫 actions 並把值傳過去
    this.$store.dispatch("getList",day)
}
我們可以在 store 裡面開啟 strict: true 嚴謹模式。開啟後我們就只能透過 Mutations 來改 state 的值,否則會收到警告。
官方建議開發時可以將 strict: true 開啟,但產品上線後可以關閉,因為比較耗資源。
const store = new Vuex.Store({
  strict: true,
  state: {
      day : 0,
      list:[]
  },
  mutations: {
    SETDAY(state,day){
        state.day = day
    },
    SETLIST(state,list){
        state.list = list
    },
  },
  actions: {
   getList(context,data){
       context.commit("SETDAY",day)
       return axios.get(apiUrl)
       .then(res=>{
           context.commit("SETLIST",res.data)
       })
   }
  },
  getters: 
    getDay: function (state) {
      return state.day
    }
  }
});
this.store.state的取值方法?而在元件中,除了透過 this.store.state 將值從 Vuex 取出,我們也可以透過 mapState 等方法。
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
意思很直覺,比如 mapState 可以提取 state 的資料、mapActions 可以提取 actions 的方法,以此類推 ~ 所以我們若要在元件中提取 vuex 的值或方法,也可以這麼寫 :
export default {
  name: 'card',
  computed: {
    ...mapGetters([
      'getDay'
    ]),
    ...mapState([
      'day'
    ])
  },
  methods: {
    ...mapActions([
      'getList'
    ]),
    ...mapMutations([
      'SETDAY','SETDAY'
    ])
  }
}
最後是 Modules 。當你的 store 日漸複雜,我們就可以透過 Modules,來整理你的 Vuex。
const block1 = {
 state: {
  // 資料儲存的地方
 },
 mutations: {
  // 透過 mutation 修改資料狀態
 },
 actions: {
  // 打 API 的地方與操作方法的地方
 },
 getters: {
   // 取得後端傳來的資料後可做修改的地方
 }
}
const block2 = {
 state: {
  // 資料儲存的地方
 },
 mutations: {
  // 透過 mutation 修改資料狀態
 },
 actions: {
  // 打 API 的地方與操作方法的地方
 },
 getters: {
   // 取得後端傳來的資料後可做修改的地方
 }
}
const store = new Vuex.Store({
 modules: {
   block1: block1,
   block2: block2
 }
});
參考文章 :
Vuex 基本入門 Day 8
[Vue.js 手牽手,一起嗑光全家桶 ] 主廚推薦 - 共享式集中數據管理大雜燴
[Vue] Vuex 是什麼? 怎麼用? — State、Mutations (1/5)